#include "playstate.h"
#include "commonFunc.h"

playstate::playstate(ptrContainer* container, statewrapper* wrapper) :
    basestate(container, wrapper)
{
}

playstate::~playstate(){
}

void playstate::draw(int &drawtime){
        //CLEAR SCREEN
        glClear(GL_COLOR_BUFFER_BIT);

        //Get percentage progress
        int prevdrawtime = drawtime;
        drawtime = SDL_GetTicks();
        double progress = ((double)(drawtime-prevdrawtime))/TICK_TIME;
        //DRAW SCREEN

        drawBackground(*g_container->bg);
        drawAll(*g_container->towerlist);
        drawAll(*g_container->unitlist, progress);
        drawAll(*g_container->misslelist);
        drawAll(*g_container->particlelist, *g_container);
        g_container->m->draw();
        g_container->g->draw(*g_container);

        //PLACE ON SCREEN
        SDL_GL_SwapBuffers();
}

bool playstate::keyDown(SDL_Event &event){
    return true;
}

bool playstate::update(int &endtime, int &ticktime){
    bool cont = true;
    static int numToWave = 0;

    handleEvents(cont, numToWave, *g_container);
    
    //HANDLE TIME
    prevendtime = endtime;
    endtime = SDL_GetTicks();
    //per is percentage of a tick since last loop
    double per = ((double)(endtime-prevendtime))/TICK_TIME;
    //update the next wave counter
    if (g_container->unitlist->size() == 0)
    {
        double ms = ((double)(endtime-prevendtime))/1000;
        g_container->g->updateTime(ms);
    }
    
    
    //Move all the missles based on the percentage generated
    moveAll(*g_container->misslelist, per, *g_container);
    
    //Update the tower targets
    updateTowerTargets(*g_container, endtime-prevendtime);
        
    //Update Particles
    updateParticles(*g_container, ((float)(endtime-prevendtime))/1000);
    
    //HANDLE TICKS
    if (endtime > ticktime+TICK_TIME)
    {
        static int spawns = 1;
        //CHECK FOR PATH AND SPAWN ENEMIES
        wave(*g_container);
        //After spawning units reset spawn count to 0
        numToWave = 0;
        
        //Handle dead units and such
        grimReaper(*g_container, spawns);
        if (g_container->theplayer->curhp < 1){
            cont = false;
        }
        
        //Find the time of the next tick
        ticktime += TICK_TIME;
    }
    return cont;
}

void playstate::enterstate(){
    prevendtime = SDL_GetTicks();
}
